//
//  LTWebViewController.m
//  LearnTeacher
//
//  Created by 高刘通 on 2024/6/7.
//

#import "LTWebViewController.h"
#import "WebKit/WebKit.h"
#import "AppDelegate.h"
#import "LTTabbarFix.h"

@interface LTWebViewController ()<WKNavigationDelegate, WKUIDelegate>
@property(strong, nonatomic) WKWebView *webView;
@property(strong, nonatomic) NSString *url;
@end

@implementation LTWebViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.webView];
    NSURL *requestUrl = [NSURL URLWithString:self.url];
    NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
    [self.webView loadRequest:request];
    if (self.fromTabbar) {
        self.webView.top = 0;
        self.webView.height = UIScreen.mainScreen.bounds.size.height - [self safeBottom] - 49 - self.webView.top;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadWebView) name:@"reloadWebView" object:nil];
}

- (CGFloat)safeBottom {
    return [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
}

- (void)loadUrl:(NSString *)url {
    _url = url;
    if ([url containsString:@"?"]) {
        _url = [NSString stringWithFormat:@"%@&statusBarHeight=%ld",_url, (NSInteger)[UIApplication sharedApplication].statusBarFrame.size.height];
    }else {
        _url = [NSString stringWithFormat:@"%@?statusBarHeight=%ld",_url, (NSInteger)[UIApplication sharedApplication].statusBarFrame.size.height];
    }
    NSLog(@"loadUrl = %@", _url);
}

- (void)reloadWebView {
    [self.webView reload];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
}

//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//    
//    decisionHandler(WKNavigationResponsePolicyAllow);
//}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *scheme = navigationAction.request.URL.scheme;
    if ([scheme.lowercaseString isEqualToString:@"learnteacher"]) {
        NSString *host = navigationAction.request.URL.host;
        NSLog(@"%@", navigationAction.request.URL);
        NSLog(@"%@", navigationAction.request.URL.host);
        if ([host.lowercaseString isEqualToString:@"goback"]) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        if ([host.lowercaseString containsString:@"opentabbar"] || [host isEqualToString:@"opentabbar"]) {
            [self.navigationController popViewControllerAnimated:NO];
            UITabBarController *tabViewController = (UITabBarController *) appDelegate.window.rootViewController;
            [tabViewController setSelectedIndex:1];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadWebView" object:nil];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (BOOL)shouldUpdateFocusInContext:(nonnull UIFocusUpdateContext *)context {
    return NO;
}

- (CGSize)sizeForChildContentContainer:(nonnull id<UIContentContainer>)container withParentContainerSize:(CGSize)parentSize {
    return CGSizeZero;
}

- (WKWebView *)webView {
    if(_webView == nil) {
        WKUserContentController *wcc = [[WKUserContentController alloc] init];
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.allowsAirPlayForMediaPlayback = YES;
        configuration.allowsInlineMediaPlayback = YES;
        configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
        configuration.userContentController = wcc;//[[WKUserContentController alloc] init];
        WKPreferences* preferences = [NSClassFromString(@"WKPreferences") new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        configuration.preferences = preferences;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) configuration:configuration];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.opaque = NO;
        if (@available(iOS 16.4, *)) {
            _webView.inspectable = YES;
        } else {
            // Fallback on earlier versions
        }
    }
    return _webView;
}

@end
